<?php

namespace App\Http\Services;

use App\Http\Model\SendPhoneNumber;
use Illuminate\Support\Facades\Redis;

class SendPhoneNumberServices extends CommonServices
{
    const REDIS_NAME = 'SENDPHONE:';

    public function __construct()
    {
        $this->phoneNumber = new SendPhoneNumber();
    }

    public function getList()
    {
        return $this->phoneNumber->getPhoneList();
    }

    /*
     * @param [$phone_id]   电话id
     * @param [$user_id]   用户id
     * */
    public function set_phone_cache($user_id, $phone_id)
    {
        $code = 205;
        do {
            $phone_status = $this->phoneNumber->getPhoneStatus($phone_id);
            if (empty($phone_status)) {
                $code = 206;
                break;//手机号码不存在
            }
            $user = self::REDIS_NAME . $user_id;
            $phone = self::REDIS_NAME . $phone_status->phone;
            $hashUserAll =$this->phoneNumber->get_all_cache($user);
            if(!empty($hashUserAll) && $hashUserAll['phone'] != $phone_status->phone){
                $code = 208 ;//用户认领手机号不是当前号码
                break;
            }
            // 用户redis 为空  或不为空 手机号码匹配
            $hincrby = Redis::hincrby($phone, 'inc', 1);//原子性操作
            //判断用户是否领取过
            //首次 可跳转
            $cache_data['user_id'] = $user_id;
            $cache_data['phone'] = $phone_status->phone;

            if ($hincrby == 1) {
                //首次 可跳转
                $this->phoneNumber->set_user_cache($user,$cache_data);
                $this->phoneNumber->set_user_cache($phone,$cache_data);
                break;
            }
            //检测是否被领取
            $hashAll =$this->phoneNumber->get_all_cache($phone);
            if (empty($hashAll['user_id'])) {
                $code = 206;
                break;
            }
            if ($hashAll['user_id'] != $user_id) {
                $code = 207;//已经被别的用户放入暂缓区
                break;
            }
        } while (false);
        return $code;
    }


}